#!/bin/bash
set -e

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

function download_ncbi-vdb() {
  echo "# ncbi-vdb正在下载"
  wget -t 40 -c -P "$1" https://github.com/ncbi/ncbi-vdb/archive/refs/tags/3.0.0.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# ncbi-vdb已经下载成功\033[0m"
  else
    echo -e "\033[31m# ncbi-vdb下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_ncbi-vdb() {
  echo "# ncbi-vdb正在安装"
  tar xf "$1"/3.0.0.tar.gz -C "$1" && rm -rf "$1"/3.0.0.tar.gz
  cd "$1"/ncbi-vdb-3.0.0 && cp -r interfaces/cc/gcc/arm64 interfaces/cc/gcc/aarch64
  #该处问题是由于官方将aarch64修改为arm64导致：https://github.com/ncbi/ncbi-vdb/pull/50，在使用gcc构建时，
  #ARCH=aarch64而不是arm64，所以构建正在寻找的interfaces/cc/gcc/aarch64并不存在：https://github.com/ncbi/ncbi-vdb/issues/65，
  #构建时通过将interfaces/cc/gcc/arm拷贝为interfaces/cc/gcc/aarch64可以解决问题：https://github.com/ncbi/ncbi-vdb/issues/72，
  #此方案为临时解决方案，若社区后续对此有修改，可通过官网了解：https://github.com/ncbi/ncbi-vdb。
  ./configure --relative-build-out-dir --build-prefix="$2"/ncbi-vdb-3.0.0 --prefix="$2"/ncbi-vdb-3.0.0
  make -j $(nproc) && make install
  echo -e "\033[1;32;1m# ncbi-vdb已经安装完毕\033[0m"
}

function install_development() {
  yum install -y wget git tar libatomic environment-modules glibc-devel make perl cmake libstdc++-static fuse-devel libxml2-devel file-devel
  source /etc/profile
}

function write_ncbi-vdb_module() {
  cat >"$1/ncbi-vdb-3.0.0/ncbi-vdb_modulefiles" <<EOF
#%Module1.0
conflict ncbi-vdb
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set NCBI_VDB \$pwd
setenv NCBI_VDB \$NCBI_VDB
prepend-path LD_LIBRARY_PATH \$NCBI_VDB/lib64
EOF
}

function main() {
  is_check_build_install_directory "$1" "$2" "ncbi-vdb-3.0.0.sh"
  is_check_build_equal "$1" "$2"
  install_development
  download_ncbi-vdb "$1"
  install_ncbi-vdb "$1" "$2"
  write_ncbi-vdb_module "$2"
  rm -rf "$1"/ncbi-vdb-3.0.0
}

main "$@"
